import requests
import json
from auto_interface.parameter_case.login_parameter import Login_par

# class Login():
#     def __init__(self):
#         try:
#             self.url = Login_par.login_url + Login_par.login_path
#             self.headers = {"Content-Type": "application/json"}  # 1. 必须通过headers指定请求内容类型为json
#             self.data = {"id": Login_par.username, "password": Login_par.password}
#             self.data = json.dumps(self.data)  # 2. 序列化成字符串\
#         except Exception:
#             return '请检查参数'

class Token_rw():
    """
    token写入读取
    """
    file_path = '../parameter_case/token_parameter.py'

    def token_w(self, value):
        file_w = open(Token_rw.file_path, "w")
        file_w.write(value)
    def token_r(self):
        file_r = open(Token_rw.file_path, "r")
        return file_r.read()

class Base_com():
    def __init__(self):
        self.url = Login_par.login_url + Login_par.login_path
        self.headers = {"Content-Type": "application/json"}  # 1. 必须通过headers指定请求内容类型为json
        self.data = {"id": Login_par.username, "password": Login_par.password}
        self.data = json.dumps(self.data)  # 2. 序列化成字符串

    def login(self):
        self.response = requests.post(url=self.url, headers=self.headers, data=self.data)
        print("sssssssssssssssssssssssssssssss")
        flag = self.response.json().get("flag")
        if flag == "T":
            # print(self.response.json())
            token = self.response.json().get("data").get("refreshToken")
            Token_rw().token_w(token)
        elif flag == "F":
            erro_info = self.response.json().get("errorInfo")
            return False, erro_info, "登录错误"
        else:
            return False, self.response.json(), "登录错误"

    def post_requests(self,  login_path, data, ass_par, login_url=Login_par.login_url):
        try:
            url = login_url + login_path
            # print(url)
        except Exception as E:
            return False, E, "路径错误"

        token = Token_rw().token_r()
        try:
            while token is "":
                self.login()
                token = Token_rw().token_r()
            # print("sfsfadsfadfsafdsf\n%s" % token)
            headers = {"charset": "UTF-8", "Content-Type": "application/json", "epToken": "%s" % token}
            response = requests.post(url=url, headers=headers, data=data.encode('utf-8'))
            # print("请求信息：\n %s \n%s \n%s" % (url, headers, data))
            try:
                status = response.json().get("status")
            except Exception as E:
                # print("获取返回状态失败：%s" % E)
                return False, response, E

            try:
                ass_value = response.json()
            except Exception as E:
                return False, response, E

            if status == "1":
                try:
                    assert ass_par in ass_value
                    # for i in ass_value.values():
                    # 遍历返回结果中的键值
                    #     if i == ass_par:
                    #         assert ass_value[ass_par] == ass_par
                    # print("校验通过")
                    return True, ass_value
                except Exception as E:
                    # print("校验失败：", E, ass_value.values())
                    return False, ass_value, E
            elif 'token cather user fail' in str(ass_value):
                print("token错误：", response.json())
                return False, ass_value, "token错误"
            else:
                return False, ass_value, "请求错误"

                # try:
                #     assert "重新登录" in response.json().get("errorInfo")
                #     self.login()
                #     token = filehandle.read()
                # except:
                #     print("重新登录错误：", response.json())
                #     return False, response.json(), "重新登录错误"
        except Exception as E:
            return False, E, "请求异常"

if __name__ == '__main__':
    Base_com().login()











        # data = json.dumps(data)
        # data = json.loads(data)
        # 转换格式，json.dumps()用于将字典形式的数据转化为字符串，json.loads()用于将字符串形式的数据转化为字典

        # response = requests.post(url=url, headers=headers, data=data.encode('utf-8'))
        # # print("请求信息：\n %s \n%s \n%s" % (url, headers, data))
        # try:
        #     status = response.json().get("status")
        # except Exception as E:
        #     # print("获取返回状态失败：%s" % E)
        #     return False, response, E
        #
        # try:
        #     ass_value = response.json()
        # except Exception as E:
        #     return False, response, E
        #
        # if status == "1":
        #     try:
        #         assert ass_par in ass_value
        #         # for i in ass_value.values():
        #         # 遍历返回结果中的键值
        #         #     if i == ass_par:
        #         #         assert ass_value[ass_par] == ass_par
        #         # print("校验通过")
        #         return True, ass_value
        #     except Exception as E:
        #         # print("校验失败：", E, ass_value.values())
        #         return False, ass_value, E
        # else:
        #     # print("接口错误：", response.json())
        #     return False, ass_value, "接口错误"




# ass_par = ("2-status-1", "2-status-1")
# print(len(ass_par))

# for ass in ass_par:
#     print("分割数：%s" % len(ass.split("-")))
#     print(ass.split("-"))
#     layer = ass.split("-")[0]
#     print(layer)
#     value = ass.split("-")[1]
#     print(value)
#     ass = ass.split("-")[2]
#     print(ass)